//
//  InputWordsViewController.m
//  NotMadLibs
//
//  Created by crpatte2 on 11/2/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "InputWordsViewController.h"


@implementation InputWordsViewController

@synthesize submit, excerpt, typesArray, inputtedWords, scrollView, controller, background;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    inputBoxes = [[NSMutableArray alloc] init];
    
    NSString *filename = [excerpt valueForKeyPath:@"file"];
    NSString *path = [[NSBundle mainBundle] pathForResource:filename ofType:@"txt"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
        NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *docDirectory = [documentPaths objectAtIndex:0];
        path = [NSString stringWithFormat:@"%@/%@.txt", docDirectory, filename];
    }
    
    NSString *text = [NSString stringWithContentsOfFile:path
                                     encoding:NSUTF8StringEncoding
                                        error:NULL];
    
    typesArray = [[NSMutableArray alloc] init];
    [self parseInput:text];
    int numWords = [typesArray count];
    
    scrollView.frame = CGRectMake(0, 0, 320, 340);
    //initialize content size based on the number of labels/word inputs we need
    [scrollView setContentSize:CGSizeMake(320, 50*numWords+200)];
    [scrollView setBackgroundColor:[UIColor blackColor]];
    
    
    controller.frame = CGRectMake(0, 0, 320, 340);
    [controller setBounds:CGRectMake(0, 0, 320, 50*numWords+200)];
    
    // initialize locations
    yLocInput = 60;
    yLocLabel = 60;
    xLocInput = 120;
    xLocLabel = 20;
    widthLabel = 90;
    heightLabel = 35;
    widthInput = 180;
    heightInput = 35;

    for (int i = 0; i < numWords; i++) { 
        UILabel *test = [[UILabel alloc] initWithFrame:CGRectMake(xLocLabel, yLocLabel, widthLabel, heightLabel)];
        test.text = [typesArray objectAtIndex:i];
        [test setBaselineAdjustment:UIBaselineAdjustmentAlignBaselines];
        [test setBackgroundColor:[UIColor blackColor]];
        [test setTextColor:[UIColor whiteColor]];
        [test setFont:[UIFont fontWithName:@"MarkerFelt-Thin"
                                      size:18.0]];
        [scrollView addSubview:test];
        [test release];
        yLocLabel += heightLabel + 10;
        
        UITextField *testText = [[UITextField alloc] initWithFrame:CGRectMake(xLocInput, yLocInput, widthInput, heightInput)];
        [testText setPlaceholder:[NSString stringWithFormat:@"Word #%d", i+1]];
        [testText setBorderStyle:UITextBorderStyleRoundedRect];
        [testText setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
        [testText setAutocapitalizationType:UITextAutocapitalizationTypeNone];
        [testText setAutocorrectionType:UITextAutocorrectionTypeNo];
        [testText setFont:[UIFont fontWithName:@"MarkerFelt-Thin"
                                      size:18.0]];
        [scrollView addSubview:testText];
        [testText release];
        yLocInput = yLocLabel;
        
        [inputBoxes addObject:testText];
    }
  
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction) submitClicked:(id)sender{
    inputtedWords = [[NSMutableArray alloc] init];
    int numWords = [typesArray count];
    BOOL pushNewVC = YES;
    BOOL alertBox = YES;
    
    for(int i = 0; i < numWords; i++) {
        
        NSString *word = [[inputBoxes objectAtIndex:i] text]; 
        word = [word stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        if (![word length] == 0) {
            [inputtedWords addObject:word];
        }
        else if (alertBox){
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Input all words!" message:@"Please input a word!" delegate:self cancelButtonTitle:@"Ok, I will!" otherButtonTitles:nil];
            [alert show];
            [alert release];
            pushNewVC = NO; //set this boolean indicator to false if we find words missing
            alertBox = NO; //don't alert multiple times if multiple input fields are blank
        }   
    }
    if(pushNewVC) {
        OutputPassageViewController *outVC = [[OutputPassageViewController alloc] initWithNibName:@"OutputPassageViewController" bundle:nil];
        NSString *title = [excerpt valueForKeyPath:@"file"];
        outVC.inputPath = title;
        outVC.inputtedWords = inputtedWords;
        [self.navigationController pushViewController:outVC animated:YES];
    
    }
}

-(IBAction)textDoneEditing:(id)sender{
    for (int i = 0; i < [inputBoxes count]; i++){
        [[inputBoxes objectAtIndex:i] resignFirstResponder];
    }
}

-(void) parseInput: (NSString *)input{
    NSArray *words = [input componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString *word, *achar;
    int typeCount = 0;
    int wordCount = [words count];
    for (int i = 0; i < wordCount; i++){
        word = [words objectAtIndex:i];
        for (int j = 0; j < [word length]; j++){
            achar = [NSString stringWithFormat:@"%c", [word characterAtIndex:j]];
            if ([achar isEqualToString:@"<"]){
                NSString *newInput = @"";
                NSString *tagNum = @"";
                j++;
                achar = [NSString stringWithFormat:@"%c", [word characterAtIndex:j]];
                while (![achar isEqualToString:@"_"]) {
                    if([achar isEqualToString:@"#"])
                        achar = @" ";
                    newInput = [newInput stringByAppendingString:achar];
                    j++;
                    achar = [NSString stringWithFormat:@"%c", [word characterAtIndex:j]];
                }
                j++;
                achar = [NSString stringWithFormat:@"%c", [word characterAtIndex:j]];
                while (![achar isEqualToString:@">"]) {
                    tagNum = [tagNum stringByAppendingString:achar];
                    j++;
                    achar = [NSString stringWithFormat:@"%c", [word characterAtIndex:j]];
                }
                int number = [tagNum intValue];
                if (!([newInput length] == 0) && number >= typeCount){
                    [typesArray addObject:[newInput capitalizedString]];
                    typeCount++;
                }
            }
        }
    }
}

@end
